package com;

import com.constant.ControllerConstan;
import com.constant.ServiceConstan;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import org.mybatis.generator.internal.util.StringUtility;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;


public class CommentGenerator extends DefaultCommentGenerator {
    private boolean addRemarkComments = false;

    /**
     * 设置用户配置的参数
     */
    @Override
    public void addConfigurationProperties(Properties properties) {
        super.addConfigurationProperties(properties);
        this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
        createControllerAndService(properties);
    }

    private void createControllerAndService(Properties properties) {

        String tableName = properties.getProperty("myClassName");
        String packageBaseName = properties.getProperty("myPackName");
        // 获取项目根目录
        String rootPath = System.getProperty("user.dir");
        // 拼接文件名
        String controllerName = tableName + "Controller";
        String serviceName = tableName + "Service";
        // 路径转换
        String myPackPath = packageBaseName.replaceAll("\\.", "/");
        String projectBasePath = "/src/main/java/";
        // 拼接文件在操作系统中的绝对路径
        String controllerPath = rootPath + projectBasePath + myPackPath + "/controller/" + controllerName + ".java";
        String servicePath = rootPath + projectBasePath + myPackPath + "/service/" + serviceName + ".java";
        String serviceImplPath = rootPath + projectBasePath + myPackPath + "/service/impl/" + serviceName + "Impl.java";


        // 生成controller
        extracted(controllerPath, packageBaseName, controllerName);
        // 生成service
        extractedService(servicePath, packageBaseName, serviceName);
        // 生成serviceImpl
        extractedServiceImpl(serviceImplPath, packageBaseName, serviceName);

        new File(rootPath + projectBasePath + myPackPath + "/request").mkdir();
        new File(rootPath + projectBasePath + myPackPath + "/response").mkdir();
    }

    /**
     * 给字段添加注释
     */
    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
        String remarks = introspectedColumn.getRemarks();
        //根据参数和备注信息判断是否添加备注信息
        if (addRemarkComments && StringUtility.stringHasValue(remarks)) {
            addFieldJavaDoc(field, remarks);
        }
    }

    /**
     * 给model的字段添加注释
     */
    private void addFieldJavaDoc(Field field, String remarks) {
        //文档注释开始
        field.addJavaDocLine("/**");
        //获取数据库字段的备注信息
        String[] remarkLines = remarks.split(System.getProperty("line.separator"));
        for (String remarkLine : remarkLines) {
            field.addJavaDocLine(" * " + remarkLine);
        }
//        addJavadocTag(field, false);
        field.addJavaDocLine(" */");
        field.addAnnotation("@ApiModelProperty(value = \"" + remarks + "\")");
    }

    /**
     * 下划线转驼峰
     *
     * @param input
     * @return
     */
    public static String underscoreToCamel(String input) {
        if (input == null) {
            return null;
        }
        String[] parts = input.split("_");
        StringBuilder camelCaseStr = new StringBuilder();
        for (String part : parts) {
            camelCaseStr.append(part.substring(0, 1).toUpperCase()).append(part.substring(1).toLowerCase());
        }
        return camelCaseStr.toString();
    }

    private static void extractedServiceImpl(String serviceImplPath, String packageBaseName, String serviceName) {
        File serviceImplFile = new File(serviceImplPath);
        if (!serviceImplFile.exists()) {
            serviceImplFile.getParentFile().mkdirs();
        }

        try {
            FileWriter fileWriter = new FileWriter(serviceImplFile);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(ServiceConstan.getServiceImplValue(packageBaseName + ".service.impl", serviceName));
            bufferedWriter.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void extractedService(String servicePath, String packageBaseName, String serviceName) {
        File servicefile = new File(servicePath);
        if (!servicefile.exists()) {
            servicefile.getParentFile().mkdirs();
        }

        try {
            FileWriter fileWriter = new FileWriter(servicefile);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(ServiceConstan.getValue(packageBaseName + ".service", serviceName));
            bufferedWriter.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void extracted(String controllerPath, String packageBaseName, String controllerName) {
        File controllerfile = new File(controllerPath);
        if (!controllerfile.exists()) {
            controllerfile.getParentFile().mkdirs();
        }

        try {
            FileWriter fileWriter = new FileWriter(controllerfile);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(ControllerConstan.getValue(packageBaseName + ".controller", controllerName));
            bufferedWriter.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
